package com.xmb.wechat.old;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.xmb.wechat.R;
import com.xmb.wechat.R2;
import com.xmb.wechat.application.WechatStartApplication;
import com.xmb.wechat.bean.WechatContactBean;
import com.xmb.wechat.bean.WechatLastMsgBean;
import com.xmb.wechat.bean.WechatLastMsgBean_;
import com.xmb.wechat.lsn.OnUnReadCountChangeListener;
import com.xmb.wechat.util.WechatDateFormat;
import com.xmb.wechat.view.wechat.chat.WechatDanliaoDetailActivity;
import com.xmb.wechat.widget.InputDialog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.objectbox.Box;

/**
 * 消息
 */
public class HomeFragment extends Fragment implements BaseQuickAdapter.OnItemClickListener,
        BaseQuickAdapter.OnItemLongClickListener {

    @BindView(R2.id.iv_search)
    ImageView    ivSearch;
    @BindView(R2.id.iv_add)
    ImageView    ivAdd;
    @BindView(R2.id.rv)
    RecyclerView rv;
    Unbinder unbinder;
    private WechatLastMsgAdapter   adapter;
    private Box<WechatLastMsgBean> lastMsgBeanBox;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_message, container, false);
        unbinder = ButterKnife.bind(this, rootView);
        adapter = new WechatLastMsgAdapter(R.layout.wechat_last_msg_item, null);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        rv.setLayoutManager(layoutManager);
        rv.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
        adapter.setOnItemLongClickListener(this);
        lastMsgBeanBox = WechatStartApplication.getBoxStore().boxFor(WechatLastMsgBean.class);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        refresh();
    }

    private void refresh() {
        ArrayList<WechatLastMsgBean> list =
                (ArrayList<WechatLastMsgBean>) lastMsgBeanBox.query().orderDesc(WechatLastMsgBean_.time).build().find();
        LogUtils.d("消息列表：" + list.size());
        adapter.getData().clear();
        adapter.addData(list);
        adapter.notifyDataSetChanged();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        //        skipToDetail(position);//暂时关闭
        showMoreAction(position);
    }

    private void skipToDetail(int position) {
        WechatLastMsgBean wechatLastMsgBean = (WechatLastMsgBean) adapter.getData().get(position);
        WechatContactBean contact = WechatStartApplication.getBoxStore().boxFor(WechatContactBean.class).get(wechatLastMsgBean.getTalkerID());
        WechatDanliaoDetailActivity.start(getActivity(), contact);
    }

    @Override
    public boolean onItemLongClick(final BaseQuickAdapter adapter, final View view, final int position) {
        showMoreAction(position);
        return true;
    }

    private void showMoreAction(int position) {
        final WechatLastMsgBean wechatLastMsgBean =
                (WechatLastMsgBean) adapter.getData().get(position);
        String[] items = wechatLastMsgBean.getUnReadCount() > 0 ? new String[]{"标记为已读", "设置时间",
                "删除"} : new String[]{"标记为未读", "设置时间", "删除"};
        new AlertDialog.Builder(getActivity()).setItems(items,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                if (wechatLastMsgBean.getUnReadCount() > 0) {
                                    setReadCount0(wechatLastMsgBean);
                                } else {
                                    setUnReadCount(wechatLastMsgBean, position);
                                }
                                break;
                            case 1:
                                setLastMsgTime(wechatLastMsgBean, position);
                                break;
                            case 2:
                                deleteLastMsg(wechatLastMsgBean, position);
                                break;
                        }
                    }
                }).setNegativeButton("取消", null).show();
    }

    //标记为已读
    private void setReadCount0(WechatLastMsgBean wechatLastMsgBean) {
        wechatLastMsgBean.setUnReadCount(0);
        lastMsgBeanBox.put(wechatLastMsgBean);
        adapter.notifyDataSetChanged();
        //通知底部的数字更新：
        notifyBottomCountChange();
    }

    //标记未读
    private void setUnReadCount(final WechatLastMsgBean wechatLastMsgBean, int position) {
        InputDialog.showInputDialog(getActivity(), "设置未读数量", "", EditorInfo.TYPE_CLASS_PHONE,
                new InputDialog.OnInputDialogListener() {
                    @Override
                    public void onCancelClicked() {
                    }

                    @Override
                    public void onOKClicked(Dialog dialog, String inputText) {
                        try {
                            int count = Integer.parseInt(inputText);
                            if (count < 0)
                                throw new NumberFormatException();
                            wechatLastMsgBean.setUnReadCount(count);
                            lastMsgBeanBox.put(wechatLastMsgBean);
                            adapter.notifyDataSetChanged();
                            dialog.dismiss();
                            //通知底部的数字更新：
                            notifyBottomCountChange();
                        } catch (NumberFormatException e) {
                            ToastUtils.showShort("输入的数字不正确");
                        }
                    }
                });
    }

    private void notifyBottomCountChange() {
        ((OnUnReadCountChangeListener) getActivity()).onUnReadCountChange();
    }

    //设置时间
    private void setLastMsgTime(final WechatLastMsgBean wechatLastMsgBean, int position) {

        TimePickerView pvTime = new TimePickerBuilder(getContext(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                wechatLastMsgBean.setTime(date);
                lastMsgBeanBox.put(wechatLastMsgBean);
                Collections.sort(adapter.getData());//按时间排序
                adapter.notifyDataSetChanged();
            }
        }).setType(new boolean[]{true, true, true, true, true, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setTitleSize(20)//标题文字大小
                .setTitleText("时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setSubmitColor(getResources().getColor(R.color.wechat_tab_bg_green))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.wechat_tab_bg_green))//取消按钮文字颜色
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();
        pvTime.show();
    }

    //删除记录
    private void deleteLastMsg(WechatLastMsgBean wechatLastMsgBean, int position) {
        adapter.getData().remove(wechatLastMsgBean);
        lastMsgBeanBox.remove(wechatLastMsgBean);
        adapter.notifyDataSetChanged();
        //通知底部的数字更新：
        notifyBottomCountChange();
    }

    public class WechatLastMsgAdapter extends BaseQuickAdapter<WechatLastMsgBean, BaseViewHolder> {

        public WechatLastMsgAdapter(int layoutResId, @Nullable List<WechatLastMsgBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, WechatLastMsgBean vo) {
            //            helper.setText(R.id.name, vo.getTalkerName());
            helper.setText(R.id.content, vo.getMsgContent());
            //未读数量：
            helper.setText(R.id.tv_msg_count, vo.getUnReadCount() + "");
            helper.setVisible(R.id.tv_msg_count,
                    vo.getUnReadCount() > 0 && vo.getUnReadCount() < 100);
            helper.setVisible(R.id.iv_msg_count,
                    vo.getUnReadCount() >= 100);

            helper.setText(R.id.time, WechatDateFormat.formatOutsideMsgList(vo.getTime()));
            //            WechatContactBean.setupAvatarIntoImageView(vo.getAvatarSrc(), null, vo.getAvatar(),
            //                    (ImageView) helper.getView(R.id.iv_avatar), 12);
        }
    }

}
